<script setup>
import * as echarts from 'echarts';
import {Edit} from '@element-plus/icons-vue'
import PaperApis from '@/apis/paper.js'
import {useRoute, useRouter} from "vue-router";
import UseTemp from '@/stores/temp.js'
import {ElMessage} from "element-plus";

const response = ref(null)
const myChart = ref(null);
// const localStore = useLocalStore();

const route = useRoute()
let myCharts = null;
const visible = ref(false)
const currentQuestion = ref()
const router = useRouter()
const cssClass = ref('')
const computedData = ref([])
const tempStore = UseTemp()

// const

function getTableData() {
  let arr = []
  for (let i of response.value.collectStructure.content) {
    let obj = {};
    obj.type = i.tyName
    obj.qcount = i.qs.length
    let rightNum = 0
    for (let j of i.qs) {
      if (j.record && j.record.rt) {
        rightNum++;
      }
    }
    obj.num = rightNum
    obj.rate = (rightNum / i.qs.length * 100).toFixed(1)
    arr.push(obj)
  }
  return arr;
}


function drawCanvas() {
  // 获取Canvas元素和2D绘图上下文
  const canvas = document.getElementById('exam-result1');
  const ctx = canvas.getContext('2d');

  // 设置Canvas的宽度和高度
  canvas.width = 200;
  canvas.height = 200;

  // 圆环的中心坐标
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;

  // 圆环的半径
  const outerRadius = 95;
  const innerRadius = 50;

  // 圆环的起始角度和结束角度
  const startAngle = -Math.PI; // 从顶部开始绘制
  const endAngle = Math.PI * 2;

  // 过渡效果的变量
  let currentAngle = startAngle;
  const targetAngle = -Math.PI + Math.PI * 2 * (response.value.paperRecords.errorCount / response.value.paperRecords.qcount); // 完整的圆环
  const duration = 2000; // 过渡时间，单位为毫秒
  const startTime = performance.now();

  // 添加渐变效果
  const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
  gradient.addColorStop(0, '#FF6E76');
  gradient.addColorStop(0.5, '#FDDD60');
  gradient.addColorStop(1, '#58D9F9');

  // 绘制外圆
  function drawOuterCircle() {
    ctx.beginPath();
    ctx.arc(centerX, centerY, outerRadius, startAngle, endAngle);
    ctx.strokeStyle = '#E8EAED';
    ctx.lineWidth = 10;
    ctx.stroke();
  }

  // 绘制圆环
  function drawRing(angle) {
    ctx.beginPath();
    ctx.arc(centerX, centerY, outerRadius, startAngle, angle);
    ctx.strokeStyle = gradient;
    ctx.lineWidth = 10;
    ctx.stroke();
  }

  // 动画函数
  function animate(currentTime) {
    const elapsedTime = currentTime - startTime;
    const progress = Math.min(elapsedTime / duration, 1);

    // 计算当前角度
    currentAngle = startAngle + (targetAngle - startAngle) * progress;

    // 清除之前的绘制
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 重新绘制外圆和圆环
    drawOuterCircle();
    drawRing(currentAngle);

    // 如果未完成，继续动画
    if (progress < 1) {
      requestAnimationFrame(animate);
    }
  }

  // 开始动画
  requestAnimationFrame(animate);
}

function getOption(response) {


  computedData.value.map(e => {
    return {
      name: e.type,
      // value:
    }
  })
  return {
    tooltip: {
      // formatter: '{a} <br/>{b} : {c}%',
      formatter: `{b} : {c}%(${response.paperRecords.hp ? '通过' : '不通过'})`,
    },
    series: [
      // {
      //   name: 'rate',
      //   type: 'gauge',
      //   startAngle: 180,
      //   endAngle: 0,
      //   progress: {
      //     show: true
      //   },
      //   pointer: {
      //     // icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
      //     // length: '12%',
      //     width: 12,
      //     // offsetCenter: [0, '-60%'],
      //     itemStyle: {
      //       color: 'auto'
      //     }
      //   },
      //   // 分割线
      //   splitLine: {
      //     length: 20,
      //     lineStyle: {
      //       color: 'auto',
      //       width: 5
      //     }
      //   },
      //   axisTick: {
      //     length: 12,
      //     lineStyle: {
      //       color: 'auto',
      //       width: 2
      //     }
      //   },
      //   // 外环线
      //   axisLine: {
      //     lineStyle: {
      //       width: 6,
      //       color: [
      //         [0.25, '#FF6E76'],
      //         [0.5, '#FDDD60'],
      //         [0.75, '#58D9F9'],
      //         [1, '#7CFFB2']
      //       ]
      //     }
      //   },
      //   detail: {
      //     valueAnimation: true,
      //     formatter: '{value}%'
      //   },
      //   data: [
      //     {
      //       value: (paperRecords.doCount - paperRecords.errorCount) / paperRecords.qcount * 100,
      //       name: '正确率'
      //     }
      //   ]
      // }
      {
        name: '考试结果',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          {value: 1048, name: 'Search Engine'},
          {value: 735, name: 'Direct'},
          {value: 580, name: 'Email'},
          {value: 484, name: 'Union Ads'},
          {value: 300, name: 'Video Ads'}
        ]
      }
    ]
  }
}


function goToAnalys(type = 'all') {
  if (type == 'all') {
    //   前往解析页
    tempStore.setExamResult(response.value)
    router.push({
      path: '/questionBank/paper/QuestionAnalys',
      query: {
        ...route.query,
        type: type
      }
    })
  } else {
    //   如果没有错题，提示一下，并不跳转
    if (response.value.paperRecords.errorCount <= 0) {
      return ElMessage({message: '没有错题，无法查看解析', type: 'warning'})
    }
    tempStore.setExamResult(response.value)
    router.push({
      path: '/questionBank/paper/QuestionAnalys',
      query: {
        ...route.query,
        type: type
      }
    })
  }
}

function doAgain() {

}

function init() {
  PaperApis.paperResult({
    params: {
      recordsId: route.query.id,
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      structure: false
    }
  }).then(res => {
    response.value = res.data
    computedData.value = getTableData();
    nextTick(() => {

      // myCharts = echarts.init(myChart.value);
      // myCharts.setOption(getOption(res.data));
      drawCanvas()
    })

  })
}

init()

</script>

<template>
  <div class="exam-result-container">
    <div class="center-box">
      <div class="left" v-if="response">
        <div class="paperName">
          <el-icon>
            <Edit/>
          </el-icon>
          {{ response.paperRecords.name }}
        </div>
        <div class="canvas-container">
          <canvas id="exam-result1" class="result-canvas" ref="myChart"></canvas>
        </div>
        <div class="quantity">
          <div class="total">总共：{{ response.paperRecords.qcount }}题</div>
          <div class="unanswered">错题：{{ response.paperRecords.errorCount }}题</div>
        </div>

        <div class="exam-date">
          交卷时间：{{ response.paperRecords.endTime }}
        </div>
        <div>
          <!--          显示各个题型的正确率-->
          <el-table :data="computedData">
            <el-table-column label="题型" prop="type"></el-table-column>
            <el-table-column label="数量" prop="qcount"></el-table-column>
            <el-table-column label="正确率" prop="rate"></el-table-column>
          </el-table>
        </div>
      </div>
      <div class="right">
        <div class="legend">
          <div class="right"><i></i> <span>答对</span></div>
          <div class="wrong"><i></i> <span>答错</span></div>
          <div class="unanswered"><i></i> <span>未答</span></div>
          <div class="marked"><i></i> <span>标记</span></div>
        </div>
        <div class="result-icons" v-if="response">
          <div class="questionResult" v-for="(item,index) in response.collectStructure.content" :key="index">
            <div class="questionTypeTitle">{{ item.tyName }}</div>
            <div class="questionList">
              <div :class="{
                unanswered:!I.record,
                wrong:I.record&&!I.record.rt,
                marked:I.collect,
                right:I.record&&I.record.rt,
              }" class="questionList-item" v-for="(I,J) in item.qs" :key="J">
                {{ J + 1 }}
              </div>
            </div>
          </div>
        </div>

        <div class="right-btns">
          <el-button type="primary" plain @click="goToAnalys('error')">
            错题解析
          </el-button>
          <el-button type="primary" plain @click="goToAnalys('all')">
            全部解析
          </el-button>
          <el-button type="primary" @click="doAgain">
            再做一次
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@media screen and (min-width: 1400px) {
  .exam-result-container {
    width: 1400px;
  }
}


.exam-result-container {
  margin: 0 auto;
  padding: 50px 0;
}

.center-box {
  background: white;
  border-radius: 12px;
  border: 1px solid var(--gray_93);
  padding: 30px;
  display: flex;
  gap: 16px;
}

.paperName {
  color: var(--gray_70);
  font-size: 16px;
}

.exam-date {
  width: 426px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  color: var(--gray_50);
  font-size: 14px;
}

.result-icons {
  text-align: right;
  display: flex;
  justify-content: flex-end;
  flex-direction: column;
  font-size: 12px;
  color: var(--gray_20);
}

.questionResult {
  box-shadow: 0 2px 6px 0 rgba(30, 109, 148, .04);
  border-radius: 9px;
  border: 1px solid var(--gray_93);
  padding: 20px 0;

  line-height: 17px;
  font-weight: 700;
  font-size: 14px;
  margin-top: 30px;
  padding-left: 20px;
  color: var(--gray_20);
}

.right .questionList {
  display: flex;
  justify-content: start;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  align-content: start;
}

.questionList-item {
  width: 42px;
  line-height: 40px;
  text-align: center;
  border-radius: 50%;
  cursor: pointer;
}

.questionList-item.unanswered {
  background: var(--bg_white);
  border: 1px solid var(--gray_80);
  color: var(--gray_50);
}

.questionList-item.right {
  background: var(--green_a);
  border: 1px solid var(--green_n);
  color: var(--green_n);
}

.result-canvas {
  width: 150px;
  height: 150px;
}

.canvas-container {
  padding: 16px 0;
  display: flex;
  justify-content: center;
}

.quantity {

  display: flex;
  padding-left: 10px;
  margin-top: 20px;
}

.quantity > div {
  font-size: 12px;
  font-weight: 400;
  color: var(--gray_50);
}

.quantity > div + div {
  margin-left: 20px;
}

.quantity > div::before {
  content: " ";
  display: inline-block;
  width: 3px;
  height: 7px;
  border-radius: 2px;
  vertical-align: middle;
  margin-right: 3px;
}

.quantity > div.total::before {
  background: #E8EAED;

}

.quantity > div.unanswered::before {
  background: linear-gradient(180deg, #FF6E76 0%, #FDDD60 50%, #58D9F9 100%);

}

.legend {
  display: flex;
  justify-content: flex-end;
}

.legend > div {
  font-size: 12px;
  color: var(--gray_20);
  margin-left: 15px;
}

.legend > div i {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.legend > div.right i {
  border: 1px solid var(--green_n);
  background: rgba(5, 193, 183, .0784313725490196);
}

.legend > div.wrong i {
  border: 1px solid #e63c23;
  background: rgba(229, 60, 35, .0784313725490196);
}

.legend > div.unanswered i {
  border: 1px solid var(--gray_85);
  background: var(--bg_white);
}

.legend > div.marked i {
  width: 12px;
  height: 13px;
  background: var(--biaoji) no-repeat;
  background-size: 100%;
  vertical-align: middle;
  border-radius: 0;
}

.center-box > .right {
  flex: 1;
}

.questionTypeTitle {
  text-align: left;
  padding: 16px 0;
}

.right-btns {
  padding: 16px 0;
  display: flex;
  justify-content: end;
  gap: 16px;
  align-items: center;
}

.questionResult .questionList-item.wrong {
  background: var(--red_a);
  border: 1px solid var(--red_n);
  color: var(--red_n);
}

.questionList-item.marked {
  position: relative;
}

.questionList-item.marked::before {
  position: absolute;
  content: "";
  width: 12px;
  height: 12px;
  top: 0;
  right: 0;
  background: var(--biaoji) no-repeat;
  background-size: cover;
}

</style>